#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::MainWindow(QTcpSocket* s, QString Id, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    UIDesign::setMainWindowUI(ui->centralwidget);
    UIDesign::setTabUI(ui->tabWidget);
    UIDesign::setListWidgetUI(ui->groupList);
    UIDesign::setListWidgetUI(ui->listWidget);
    UIDesign::setMainButtonUI(ui->addFriend);
    UIDesign::setMainButtonUI(ui->deleteFriend);
    UIDesign::setMainButtonUI(ui->confirmFriend);
    UIDesign::setMainButtonUI(ui->createGroup);
    UIDesign::setMainButtonUI(ui->exitGroup);
    UIDesign::setMainButtonUI(ui->inviteGroup);
    UIDesign::setMainButtonUI(ui->joinGroup);
    UIDesign::setMainButtonUI(ui->pushButton);
    UIDesign::setMainButtonUI(ui->closeButton);
    UIDesign::setTextListUI(ui->lineEdit);
    UIDesign::setContentListUI(ui->showWindow);
    this->setWindowTitle("聊天界面");
    sock = s;
    //updatefunc();

    /*
    disconnect(s, SIGNAL(readyRead()), 0, 0);
    updateFriendList();
    disconnect(s, SIGNAL(readyRead()), 0, 0);
    updateGroupList();
    disconnect(s, SIGNAL(readyRead()), 0, 0);
    update_P2P_ChattingList();
    */
    ID = Id;
    current_Row = -1;
    sock_read = new QTcpSocket();
    sock_read->connectToHost("192.168.199.1", 9988);
    disconnect(s, SIGNAL(readyRead()), 0, 0);
    connect(sock_read, SIGNAL(readyRead()), this, SLOT(hadrecv()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    //QString sendData = ui->lineEdit->text();

    //发送信息的格式为#sd|myID|targetID|sendData

    //QString temp = "#sd" + "|" + ID +


    //sock->write(sendData.toUtf8());
}

void MainWindow::hadrecv()
{
    QByteArray recvorder = sock_read->readAll();
    //ui->textEdit->append(recvorder);
    //收到个人信息格式为#me|myID|targetID|index|time|name
    //收到添加好友请求为#04|myID|targetID|targetName
    //对方同意了你的添加为#14|myID|targetID|targetname
    //对方拒绝了你的添加为#24|myID|targetID|1

    QString temp(recvorder);
    qDebug() << temp;
    QStringList orders = temp.split('|');
    if(orders[0] == "#me")
    {
        int cursor = 0;
        while(cursor != listId.size() && listId[cursor] != orders[2])cursor ++;
        if(cursor == listId.size())
        {
            QMessageBox::warning(this, "警告", orders[4] + " " + "未知Id正试图通讯: " + orders[2] + " : " + orders[3]);
        }
        else
        {
            //这里可以美化

            QString name = orders[5];
            QString fromID = orders[2];
            QString time = orders[4];
            QString content = orders[3];
            qDebug() << content;

            int ret = QMessageBox::information(this, "新信息",orders[4] + " " +  "新信息：" + orders[3] + "\n" + "来自" + listName[cursor], QMessageBox::Yes | QMessageBox::No);
            if(ret == QMessageBox::Yes)
            {
                //ui->textEdit->append(orders[4]);
                //ui->textEdit->append(orders[3]);
                addWig(name, fromID, time, content);

                int line = cursor;
                communicationId = listId[line];
                qDebug() << line << "|" << communicationId;
                connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliver()));
            }



            //时间为orders[4]

            localProcess::writeChat(fromID, name, fromID, content, time, "friend");
        }
    }
    else if(orders[0] == "#04")
    {
        int ret = QMessageBox::information(this, "添加好友请求", orders[3] + "请求添加您为好友。" , QMessageBox::Yes, QMessageBox::No);
        if(ret == QMessageBox::Yes)
        {
            //返回的信号为 #13|对面的ID|我的ID|1(同意）/0（拒绝）



            //创建设置好友昵称窗口
            setFriendNickname *sfn = new setFriendNickname(orders[3], orders[2]);
            sfn->show();
            //newChatFriend(orders[2]);
            connect(sfn, SIGNAL(signalSetFriendNickname(QString, QString, QString)), this, SLOT(createrec(QString, QString , QString)));
            //创建好友记录



            QString retText = "#13|" + orders[2] + "|" + ID + "|" + creatingNickname;
            sock->write(retText.toUtf8());
        }
        else
        {
            QString retText = "#23|" + orders[2] + "|" + ID + "|1";
            sock->write(retText.toUtf8());
        }
    }
    else if(orders[0] == "#14")
    {
        qDebug() << "#14";
        QMessageBox::information(this, "提示", "您所发送的好友申请对方已通过！");
    }
    else if(orders[0] == "#24")
    {
        qDebug() << "#24";
        QMessageBox::warning(this, "警告", "您所发送的好友申请对方拒绝辣！");
        int cursor = 0;
        while(cursor != listId.size() && listId[cursor] != orders[2])
        {
            cursor ++;
        }
        if(cursor != listId.size())
        {
            ui->listWidget->takeItem(cursor);
            listId.removeAt(cursor);
            listName.removeAt(cursor);
            listNickName.removeAt(cursor);
        }

    }


  /*
    if()
    {
        update();
    }
    else if()//收到添加好友请求
    {

    }
    */



}

void MainWindow::on_closeButton_clicked()
{
    this->close();
    emit mainclose();
}


void MainWindow::on_addFriend_clicked()//添加好友
{
    friendAdd *fa = new friendAdd(sock, ID);
    fa->show();
    //创建添加好友窗体
    qDebug() << "clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(fa, SIGNAL(addfriendclose(QString, QString, QString)), this, SLOT(createrec(QString, QString, QString)));
}


void MainWindow::createrec(QString uName, QString unId, QString nickname)
{
    creatingNickname = nickname;
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    qDebug() << uName << "|" << unId << "|" << nickname;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(unId == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = nickname + " (" + unId + ")\n" + uName;
        ui->listWidget->addItem(temp);
        listId << unId;
        listName << uName;
        listNickName << nickname;
        localProcess::newChatFriend(unId, "friend");
    }
    else
    {
        QMessageBox::information(this, "提示", "已经有此好友，无需添加");
    }

    for(int i = 0; i < listId.size(); i ++)
    {
        qDebug() << listName[i] << "|" << listId[i] << listNickName[i];
    }
}




/*
void MainWindow::updatefunc()
{
    QString reqWord = "     ";//待填写
    sock->write(reqWord.toUtf8());
    connect(sock, SIGNAL(readyRead()), this, SLOT(updateFriendList()));
}
void MainWindow::updateFriendList()
{
    QByteArray retWord = sock->readAll();
    if()
    {
        QMessageBox::warning(this, "警告", "无法更新，请联系管理员");
    }
}
*/


void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    int line = ui->listWidget->currentRow();
    communicationId = listId[line];
    qDebug() << line << "|" << communicationId;
    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliver()));
}
void MainWindow::deliver()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(testDeliver()));


    //发送信息的格式为#sd|myID|targetID|sendData


    QString sendText = ui->lineEdit->document()->toPlainText();

    QString temp = "#sd|" + ID + "|" + communicationId + "|" + sendText;

    qDebug() << temp;


    sock->write(temp.toUtf8());

}
void MainWindow::testDeliver()
{
    QByteArray feedback = sock->readAll();
    QString temp(feedback);
    QStringList feedbackList = temp.split("|");

    //发送信息的返回值为 #rd|myID|targetID|0（失败）/1（成功）|time




    if(feedbackList[3] == "0")
    {
        QMessageBox::warning(this, "警告", "发送失败，请重试");
        ui->lineEdit->clear();
    }
    else if(feedbackList[3] == "1")
    {
        QString name = feedbackList[5];
        QString fromID = feedbackList[2];
        QString time = feedbackList[4];
        QString content = ui->lineEdit->document()->toPlainText();
        qDebug() << ui->lineEdit->document()->toPlainText();

        //ui->textEdit->append(feedbackList[4]);
        //ui->textEdit->append(ui->lineEdit->placeholderText());

        //添加组件
        addWig(name, fromID, time, content);
        //feedback[4]为返回时间


        //写入到本地消息记录
        localProcess::writeChat(fromID, name, feedbackList[2], content, time, "friend");

        ui->lineEdit->clear();
    }
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
}

void MainWindow::on_deleteFriend_clicked()
{
    frienddelete *fd = new frienddelete(sock, ID);
    fd->show();
    //创建删除好友窗体
    qDebug() << "clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(fd, SIGNAL(deletefriendclose(QString)), this, SLOT(deleterec(QString)));
}

void MainWindow::deleterec(QString unId)
{
    qDebug() << unId;
    int cursor = 0;
    while(cursor != listId.size() && listId[cursor] != unId)cursor ++;
    if(cursor != listId.size())
    {
        ui->listWidget->takeItem(cursor);
        listId.removeAt(cursor);
        listName.removeAt(cursor);
        listName.removeAt(cursor);
    }
}

void MainWindow::on_createGroup_clicked()
{
    groupCreate *gc = new groupCreate(sock, ID);
    gc->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(gc, SIGNAL(creategroupclose(QString, QString)), this, SLOT(creategrouprec(QString, QString)));
}
void MainWindow::creategrouprec(QString gName, QString gID)
{
    qDebug() << gName << "|" << gID;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(gID == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = gName + " (" + gID + ")";
        ui->groupList->addItem(temp);
        listGroupId << gID;
        listGroupName << gName;
        listGroupVerify << "1";


        //xml本地化

        //newChatFriend(unId);
    }
}




void MainWindow::on_joinGroup_clicked()
{
    groupJoin *gj = new groupJoin(sock, ID);
    gj->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(gj, SIGNAL(joinGroupClose(QString,QString)), this, SLOT(joinGroupRec(QString,QString)));
}
void MainWindow::joinGroupRec(QString gName, QString gID)
{
    qDebug() << gName << "|" << gID;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(gID == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = gName + " (" + gID + ")";
        ui->groupList->addItem(temp);
        listGroupId << gID;
        listGroupName << gName;
        listGroupVerify << "0";


        //xml本地化

        //newChatFriend(unId);
    }
}

void MainWindow::on_inviteGroup_clicked()
{
    //要获取当前群聊
    groupInvite *gi = new groupInvite(sock, ID, gID);
    gi->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
}



void MainWindow::updateFriendList()
{
    //发过去的指令
    //{
    //  "order" : "UpdateFriendList"
    //  "myID" ： QString
    //}
    //返回的类型
    //{
    //  "FriendName" ： QString
    //  "FriendId" : QString
    //  "FriendNickName" ：QString
    listId.clear();
    listName.clear();
    listNickName.clear();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(decodeFriendList()));
    QJsonObject request;
    request.insert("order", "UpdateFriendList");
    request.insert("myID", ID);
    QJsonDocument temp(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
}


void MainWindow::decodeFriendList()
{
    QByteArray feedback = sock->readAll();
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        if(feedback_doc.isArray())
        {
            QJsonArray feedback_array = feedback_doc.array();
            int size = feedback_array.size();
            for(int i = 0; i < size; i ++)
            {
                QStringList objItem;
                QJsonValue val = feedback_array.at(i);
                if(val.isObject())
                {
                    QJsonObject obj =  val.toObject();
                    QJsonObject::iterator it;
                    for(it = obj.begin(); it != obj.end(); it++)
                    {
                        if(it.value().isString())
                        {
                            QString cnv = it.value().toString();
                            objItem << cnv;
                        }
                    }
                }
                //objItem[0]:FriendName; objItem[1]:FriendId; objItem[2]:FriendVerify
                QString temp = objItem[2] + " (" + objItem[1] + ")\n" + objItem[0];
                ui->listWidget->addItem(temp);
                listName << objItem[0];
                listId << objItem[1];
                listNickName << objItem[2];
                /*
                 * 1.获取最后一条聊天消息时间
                 * 2、调用请求函数返回指定list
                 * 3、调用本地写入函数
                */
            }


            //剩下的得本地化

        }
    }
}

void MainWindow::updateGroupList()
{

    //发过去的指令
    //{
    //  "order" : "UpdateGroupList"
    //  "myID" ： QString
    //}
    //返回的类型
    //{
    //  "GroupName" ： QString
    //  "GroupId" : QString
    //  "GroupVerify" ：QString 0（不是群主）/1（是群主）
    //}
    listGroupId.clear();
    listGroupName.clear();
    listGroupVerify.clear();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(decodeGroupList()));
    QJsonObject request;
    request.insert("order", "UpdateGroupList");
    request.insert("myID", ID);
    QJsonDocument temp;
    temp.setObject(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
}
void MainWindow::decodeGroupList()
{
    QByteArray feedback = sock->readAll();
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        if(feedback_doc.isArray())
        {
            QJsonArray feedback_array = feedback_doc.array();
            int size = feedback_array.size();
            for(int i = 0; i < size; i ++)
            {
                QStringList objItem;
                QJsonValue val = feedback_array.at(i);
                if(val.isObject())
                {
                    QJsonObject obj =  val.toObject();
                    QJsonObject::iterator it;
                    for(it = obj.begin(); it != obj.end(); it++)
                    {
                        if(it.value().isString())
                        {
                            QString cnv = it.value().toString();
                            objItem << cnv;
                        }
                    }
                }
                //objItem[0]:GroupName; objItem[1]:GroupId; objItem[2]:GroupVerify
                ui->groupList->addItem(objItem[0] + "(" + objItem[1] + ")");
                listGroupId << objItem[0];
                listGroupName << objItem[1];
                listGroupVerify << objItem[2];
            }


            //剩下的得本地化

        }
    }
}


/*

void MainWindow::update_P2P_ChattingList()
{
    //发过去的指令
    //{
    //  "order" : "UpdateGroupList"
    //  "myID" ： QString
    //  "targetID" : QString

    //}
    //返回的类型
    //{
    //  "GroupName" ： QString
    //  "GroupId" : QString
    //  "GroupVerify" ：QString 0（不是群主）/1（是群主）
    //}
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    int friendSize = listId.size();
    for(int i = 0; i < friendSize; i ++)
    {
        connect(sock, SIGNAL(readyRead()), this, SLOT(decode_P2P_ChattingList(listId[i])));


    }



}
*/




void MainWindow::on_exitGroup_clicked()
{
    if(ui->tabWidget->currentIndex() == 0)
    {
        QMessageBox::information(this, "提示", "请打开群聊界面进行选择");
    }
    else if(listGroupId.size() == 0) QMessageBox::information(this, "提示", "您没有群聊");
    else
    {
        current_Row = ui->groupList->currentRow();
        int ret = QMessageBox::information(this, "提示", "你想退出群:" + listGroupName[current_Row] + " 吗？", QMessageBox::Yes, QMessageBox::No);
        if(ret == QMessageBox::Yes)
        {
            //发送区
        }
    }


}




void MainWindow::on_groupList_itemClicked(QListWidgetItem *item)
{
    current_Row = ui->groupList->currentRow();
    gID = listGroupId[current_Row];
}

void MainWindow::addWig(QString name, QString fromID, QString time, QString content){

    chatContent* chCo = new chatContent(name, fromID, time, content);
    QListWidgetItem* item = new QListWidgetItem(ui->showWindow);
    ui->showWindow->addItem(item);
    ui->showWindow->setItemWidget(item, chCo);

    item->setSizeHint(QSize(chCo->width(), chCo->height()));
    chCo->design(fromID);
    chCo->show();
}
